package com.dynamic.mybatis.core.utils;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ClassUtils;
import net.sf.cglib.beans.BeanCopier;
import net.sf.cglib.beans.BeanMap;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.beans.PropertyDescriptor;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.*;

/**
 * @Description 底层使用cglib拷贝， 注意对象属性的set方法使用Builder模式无法进行拷贝
 * @Author xs
 * @Date 2021/11/10 18:01
 */
public class BeanUtils {


    public static byte[] serialize(Object bean) {
        try (
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        ) {
            objectOutputStream.writeObject(bean);
            objectOutputStream.flush();
            return byteArrayOutputStream.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T deserialize(byte[] bytes) {
        try (
                ByteArrayInputStream byteArrayOutputStream = new ByteArrayInputStream(bytes);
                ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayOutputStream);
        ) {
            return (T) objectInputStream.readObject();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T serializeCopy(Object bean) {
        return BeanUtils.deserialize(BeanUtils.serialize(bean));
    }


    public static Map beanToMap(Object bean) {
        return bean == null ? null : bean instanceof Map ? (Map) bean : BeanMap.create(bean);
    }

    public static <T> T copy(T bean) {
        T target = ClassUtils.newInstance((Class<T>) bean.getClass());
        BeanCopier.create(bean.getClass(), bean.getClass(), false).copy(bean, target, null);
        return target;
    }

    /**
     * 将source字段拷贝到target中，只拷贝target中没有的字段 ，浅拷贝数据
     *
     * @param source 原数据
     * @param target 被合并对象
     */
    public static <S, T> T copy(S source, T target) {
        return copy(source, target, Boolean.TRUE);
    }


    public static <S, T> T copy(S source, T target, String... ignoreProperties) {
        return copy(source, target, Boolean.TRUE, ignoreProperties);
    }

    public static <S, T> T copy(S source, T target, boolean ignoreEmpty, String... ignoreProperties) {
        Map targetMap = copyGetMap(source, target, ignoreEmpty, ignoreProperties);
        return getBean(targetMap);
    }

    public static <T> T getBean(Map map) {
        return (T) (map instanceof Map && !(map instanceof BeanMap) ? map : ((BeanMap) map).getBean());
    }


    public static <T> Map copyGetMap(T bean) {
        return copyGetMap(bean, ClassUtils.newInstance((Class<T>) bean.getClass()), Boolean.TRUE);
    }

    public static <T> Map copyGetMap(T source, T target, boolean ignoreEmpty, String... ignoreProperties) {
        Map sm = beanToMap(source);
        Map tm = beanToMap(target);
        if (sm == null) {
            return tm;
        }
        Map temp;
        if (ignoreEmpty) {
            temp = new MyHashMap(ignoreProperties);
            temp.putAll(sm);
        } else {
            temp = sm;
        }
        tm.putAll(temp);
        return tm;
    }

    static class MyHashMap<K, V> extends HashMap<K, V> {
        private Object[] ignoreProperties;

        public MyHashMap(Object[] ignoreProperties) {
            this.ignoreProperties = ignoreProperties;
        }

        public MyHashMap() {
        }

        @Override
        public void putAll(Map<? extends K, ? extends V> m) {
            for (Map.Entry e : m.entrySet()) {
                if (StringUtils.isNotEmpty(e.getValue()) && (ignoreProperties == null || ignoreProperties.length < 1 || Arrays.binarySearch(ignoreProperties, e.getKey()) < 0)) {
                    super.put((K) e.getKey(), (V) e.getValue());
                }
            }
        }
    }


    public static String[] getNullPropertyNames(Object source) {
        BeanWrapper src = new BeanWrapperImpl(source);
        PropertyDescriptor[] pds = src.getPropertyDescriptors();
        Set<String> emptyNames = new HashSet<>();
        for (PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) {
                emptyNames.add(pd.getName());
            }
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    /**
     * 　* @Description: 忽略source中值为空的属性拷贝
     *
     */
    public static <T> T copyProperties(T source, T target) {
        org.springframework.beans.BeanUtils.copyProperties(source, target, getNullPropertyNames(source));
        return target;
    }


    public static void main(String[] args) {

        Boolean bean = true;

        Map map = BeanUtils.beanToMap(bean);

        System.out.println(map);

    }


    public static <T> Object getValueByPath(T object, String path) {
        if (StringUtils.isEmpty(path)) {
            return object;
        }
        return getMapValueByPath(beanToMap(object), path);
    }


    public static Object getMapValueByPath(Map<String, Object> map, String path) {
        if (path == null || path.length() == 0) {
            return null;
        }
        String[] paths = path.split("\\.");
        Object newObj = null;

        for (int i = 0; i < paths.length; i++) {
            String s = paths[i];
            if (i == 0) {
                newObj = map.get(s);
                continue;
            }
            newObj = getObject(newObj, s);
        }
        return newObj;
    }

    private static Object getObject(Object newObj, String s) {
        if (newObj instanceof Map) {
            return ((Map) newObj).get(s);
        }
        if (newObj instanceof List) {
            List<Object> list = new ArrayList<>();
            List<Object> o = (List<Object>) newObj;
            for (Object object : o) {
                list.add(getObjectFromList(object, s));
            }
            return list;
        }
        if (newObj instanceof JSONObject) {
            return ((JSONObject) newObj).get(s);
        }
        if (newObj instanceof JSONArray) {
            List<Object> list = new ArrayList<>();
            List<Map> o = (List<Map>) newObj;
            for (Map map1 : o) {
                list.add(map1.get(s));
            }
            return list;
        }
        return newObj;
    }

    public static Object getObjectFromList(Object object, String s) {
        if (object instanceof Map) {
            return ((Map) object).get(s);
        }
        if (object instanceof List) {
            List<Object> list = new ArrayList<>();
            List<Object> o1 = (List<Object>) object;
            for (Object o2 : o1) {
                list.add(getObjectFromList(o2, s));
            }
            return list;
        }
        return object;
    }


}